gusucode.com > 支持向量机工具箱 - LIBSVM OSU_SVM LS_SVM源码程序 > 支持向量机工具箱 - LIBSVM OSU_SVM LS_SVM\stprtool\linear\anderson\andrdemo.m

    function result = andrdemo(action,hfigure,varargin)
% ANDRDEMO demo on Generalized Anderson's task.
%
% ANDRDEMO demonstrates the algorithms which solve 
%  the Generalized Anderson`s Task (GAT). 
%
%  The found solution (hyperplane, line in 2D) is vizualized 
%  as well as the input Gaussians which describe input classes.
%
%  Following algorithms can be tested:
%     
%  e-Optimal - Epsilon-solution of the GAT.
%  Original  - Original Anderson-Bahadur's solution for two distributions.
%  Gradient  - Algorithm using theorem of the generalized gradient methods.
%  General   - Implementation of general algorithm framework by SH10.
%  General2  - Implementation of general algorithm framework, improved.
%
% Control:
%  Algorithm  - select algorithm for testing.
%  Parameter input line - parameters for the selected algorithm
%             (see help 'given algorithm').
%  Iterations - number of iterations in one step.
%  Animation  - enable/dissable animation.
%
%  FIG2EPS     - export screen to the PostScript file.
%  Load data   - load input point sets from file.
%  Create data - call interactive program for creating sets of Gaussians.
%  Reset       - set the tested algorithm to the initial state.
%  Play        - run the tested algorithm.
%  Stop        - stop the running algorithm.
%  Step        - perform only one step.
%  Info        - display the info box.
%  Close       - close the program.
%
% See also EANDERS, OANDERS, GGANDERS, GANDERS, GANDERS2.
%

% Statistical Pattern Recognition Toolbox, Vojtech Franc, Vaclav Hlavac
% (c) Czech Technical University Prague, http://cmp.felk.cvut.cz
% Written Vojtech Franc (diploma thesis) 24.10.1999, 27.02.2000
% Modifications
% 11-June-2001, V.Franc, comments added.
% 24. 6.00 V. Hlavac, comments polished.

% constants
ALGONAMES=['e-Optimal ';'Original  ';'Gradient  ';'General   ';'General 2 '];
PREC_TITLE=['Max error (0-50) [%]';...    % e-Optimal solution
            'd(lambda,ni) (0,inf)';...    % Original Anderson`s solution
            'd( min r ) (0,inf)  ';...    % Gradient method
            'd( min r ) (0,inf)  ';...    % General solution 1
            'd( min r ) (0,inf)  '];      % General solution 2
DEF_PRECISION=[5,1e-3,0,0,0];     % default values of the precision of algo. 1,2,3,4,5
BORDER=0.5;
DATA_IDENT='Infinite sets, Normal distributions';       % M-file identifier
%PLOT_FCE='pandr2d';     % outlined ellipsoids
PLOT_FCE='pandr2df';     % outlined ellipsoids

% if number of arguments is less then 1, that means first call of this function. Every
% other calls set up at least argument action
if nargin < 1,
   action = 'initialize';
end

% what action is required ?
switch lower(action)

case 'initialize'
   % == Initialize user interface control and figure window ================

   % == Figure =============================================================
   left=0.1;
   width=0.8;
   bottom=0.1;
   height=0.8;
   hfigure=figure('Name','Anderson`s task', ...
      'Visible','off',...
      'Units','normalized', ...
       'NumberTitle','off', ...
      'Position',[left bottom width height],...
      'tag','Andrdemo',...
      'Units','normalized', ...
      'RendererMode','manual');

   % == Axes ===============================================================
   left=0.1;
   width=0.65;

   % axes for showing sets
   bottom=0.35;
   height=0.60;
   haxes1=axes(...
       'Units','normalized', ...
      'Box','on', ...
      'DrawMode','fast',...
      'NextPlot','add',...
      'Layer','top',...
      'UserData',[],...
      'Position',[left bottom width height]);
   xlabel('feature x');
   ylabel('feature y');

   % == Comment window =====================================================

   % Comment Window frame
   bottom=0.05;
   height=0.2;
   uicontrol( ...
        'Style','frame', ...
        'Units','normalized', ...
        'Position',[left bottom width height], ...
        'BackgroundColor',[0.5 0.5 0.5]);

   % Text label
   uicontrol( ...
        'Style','text', ...
        'Units','normalized', ...
        'Position',[left height-0.01 width 0.05], ...
        'BackgroundColor',[0.5 0.5 0.5], ...
        'ForegroundColor',[1 1 1], ...
        'String','Comment Window');

   % Edit window
   border=0.01;
   hconsole=uicontrol( ...
        'Style','edit', ...
        'HorizontalAlignment','left', ...
        'Units','normalized', ...
        'Max',10, ...
        'BackgroundColor',[1 1 1], ...
        'Position',[left+border bottom width-2*border height-0.05], ...
        'Enable','inactive',...
        'String','');


    % == Buttons ===========================================================
   % -- Export to EPS ---------
   width=0.1;
   left=0.75-width;
   bottom=0.95;
   height=0.04;
   hbtclose = uicontrol(...
    'Units','Normalized', ...
      'Callback','fig2eps(gcf)',...
        'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','FIG2EPS');
   %----------------------------------

   % Close button
   left=0.8;
   bottom=0.05;
   height=0.05;
   width=0.15;
   hbtclose = uicontrol(...
    'Units','Normalized', ...
      'Callback','close(gcf)',...
        'ListboxTop',0, ...
        'Position',[left bottom width height], ...
        'String','Close');

   % Info button: call stanard info box
   bottom=bottom+1.5*height;
   hbtinfo = uicontrol(...
    'Units','Normalized', ...
      'Callback','andrdemo(''info'',gcf)',...
        'ListboxTop',0, ...
        'Position',[left bottom width height], ...
        'String','Info');

   % Step button: perform one adaptation step
   bottom=bottom+1.5*height;
    hbtstep = uicontrol(...
      'Units','Normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Step', ...
      'Interruptible','off',...
      'Callback','andrdemo(''step'',gcf)');

   % Stop button: stop process of adaptation
   bottom=bottom+height;
   hbtstop = uicontrol(...
    'Units','Normalized', ...
        'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Stop', ...
      'Callback','set(gcbo,''UserData'',1)',...
      'Enable','off');

   % Play button: start up adaptation
   bottom=bottom+height;
   hbtplay = uicontrol(...
    'Units','Normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Play', ...
      'Callback','andrdemo(''play'',gcf)');

   % Reset button: set up t = 0
   bottom=bottom+height;
    hbtreset = uicontrol(...
      'Units','Normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Reset', ...
      'Callback','andrdemo(''reset'',gcf)');

   % Create data
   bottom=bottom+1.5*height;
    hbtcreat = uicontrol(...
      'Units','Normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Create data', ...
      'Callback','andrdemo(''creatdata'',gcf)');

   % Load data
   bottom=bottom+1*height;
    hbtload = uicontrol(...
      'Units','Normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'String','Load data', ...
      'Callback','andrdemo(''getfile'',gcf)');

   % == Check boxes ===============================================================

   % Make chack box to determine if a line will be drawn in one step or smoothly.
   bottom=bottom+height*1.2;
    hxbanim = uicontrol(...
    'Style','checkbox', ...
       'Units','normalized', ...
    'ListboxTop',0, ...
       'Position',[left bottom width height], ...
    'String','Animation');


   % == Popup menus ==========================================================

   % Pop up menu for the selection between algorithms
    % title
   bottom=0.95-height;
   htxalgo=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',[left bottom width 0.9*height], ...
      'String','Algorithm');
   % popup menu
   bottom=bottom-0.9*height;
   hpualgo=uicontrol( ...
      'Style','popup', ...
      'Units','normalized', ...
      'CallBack','andrdemo(''algohandler'',gcf)',...
      'Position',[left bottom width height], ...
      'UserData',1,...
      'String',ALGONAMES);


   % == Edit lines ================================================================

   bottom=0.95-3.5*height;
   % Precision of solution
   htxprec=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',[left bottom width 0.9*height], ...
      'String',PREC_TITLE(1,:));

   bottom=bottom-height;
   hedprec = uicontrol(...
    'Units','normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'Style','edit',...
      'String',num2str(DEF_PRECISION(1)) );

   % # of iterations
   bottom=bottom-1.5*height;
   htxiter=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',[left bottom width 0.9*height], ...
      'String','Iterations');

   bottom=bottom-0.9*height;
   hediter = uicontrol(...
    'Units','normalized', ...
      'ListboxTop',0, ...
        'Position',[left bottom width height], ...
      'Style','edit',...
      'String',1);

    % ==============================================================================

   % Store handlers
   handlers=struct(...
      'line',struct('handler',-1,'alpha',0,'alpha1',0,'alpha2',0,'lambda',0,'theta',0,'t',0),...
      'btstep',hbtstep,...
      'btstop',hbtstop,...
      'btclose',hbtclose,...
      'btplay',hbtplay,...
      'btreset',hbtreset,...
      'btinfo',hbtinfo,...
      'btload',hbtload,...
      'btcreat',hbtcreat,...
      'pualgo',hpualgo,...
      'console',hconsole,...
      'edprec',hedprec,...
      'editer',hediter,...
      'txprec',htxprec,...
      'axes1',haxes1,...
      'xbanim',hxbanim);

   set(hfigure,'UserData',handlers);

   % Reset adaptation, t=0
   andrdemo('reset',hfigure);

   % Put figure on desktop
   set(hfigure,'Visible','on');

   drawnow;


case 'creatdata'
   % == Invoke data set creator ============================================
   creatset('normal',2,'andrdemo','created',hfigure);


case 'created'
   % == Load new created data set ===========================================

   % get handler and make this figure active
   figure(hfigure);
   h=get(hfigure,'UserData');

   % get file name
   path=varargin{1};
   name=varargin{2};
   pathname=strcat(path,name);

   if checkdat(pathname,DATA_IDENT,2,[0 0])==1,
      file.pathname=pathname;
      file.path=path;
      file.name=name;
      set(h.btload,'UserData',file);
      andrdemo('loadsets',hfigure);
      andrdemo('reset',hfigure);
   else
      errordlg('This file does not contain required data.','Bad file','modal');
   end


case 'getfile'
   % == Invoke standard open file dialog ====================================
   % Opens file and checks if contains apropriate data, if yes loads data.

   h=get(hfigure,'UserData');

   % change path to directory
%%   wres=what('anderson');
%%   cd(wres.path);

   [name,path]=uigetfile('*.mat','Open file');
   if name~=0,
      file.pathname=strcat(path,name);
      file.path=path;
      file.name=name;
      if checkdat(file.pathname,DATA_IDENT,2,[0 0])==1,
         set(h.btload,'UserData',file);
         andrdemo('loadsets',hfigure);
         andrdemo('reset',hfigure);
      else
         errordlg('This file does not contain required data.','Bad file','modal');
      end
   end


case 'algohandler'
   % == Handler for check box 'Algorithm' =======================================
   % If new algorithm is selected then prepare data for it.

   h=get(hfigure,'UserData');

   if get(h.pualgo,'UserData') ~= get(h.pualgo,'Value'),
      set(h.pualgo,'UserData',get(h.pualgo,'Value'));

      set(h.edprec,'String',num2str(DEF_PRECISION(get(h.pualgo,'Value'))) );
      set(h.txprec,'String',PREC_TITLE(get(h.pualgo,'Value'),:));

      andrdemo('loadsets',hfigure);
      andrdemo('reset',hfigure);
   end


case 'loadsets'
   % == Load sets ==================================================================
   % Get given file name and load the data set from him.

   h=get(hfigure,'UserData');                   % uicontrol handlers

   % Get file name
   file=get(h.btload,'UserData');
   if isempty(file)==0,

      % Load sets
      sets=load(file.pathname);

      % algorithm 2 (Original Anderson`s) solution find solution for two distributions only
      if get(h.pualgo,'Value')==2,
         % get only one distribution from each class
         class1=0;
         class2=0;
         NI=[];
         NMI=[];
         NSIGMA=[];
         NK=[1 1];
         i=0;
         while i<sets.K | class1==0 |class2==0,
            i=i+1;
            if sets.I(i)==1 & class1==0,
               class1=1;
               NI=[NI,1];
               NMI=[NMI,sets.MI(:,i)];
               NSIGMA=[NSIGMA,sets.SIGMA(:,(i-1)*2+1:i*2)];
            elseif sets.I(i)==2 & class2==0,
               class2=1;
               NI=[NI,2];
               NMI=[NMI,sets.MI(:,i)];
               NSIGMA=[NSIGMA,sets.SIGMA(:,(i-1)*2+1:i*2)];
            end
         end % while

         % replace old values
         sets.MI=NMI;
         sets.SIGMA=NSIGMA;
         sets.I=NI;
         sets.K=NK;
      end % if get(h.pualgo,....
   else
      % No set is loaded.
      sets=[];
   end

   % store sets
   set(h.axes1,'UserData',sets);


case 'play'
   % == Start up the adaptation process =======================================
   % Perform the adaptation step by step until the solution is found or stop
   % button is pushed down.

   h=get(hfigure,'UserData');                      % get handlers

   % get sets
   sets=get(h.axes1,'UserData');

   % if some set is loaded then perform on step
   if isempty(sets)==0,

      % Disable buttons everything axcept
      set([h.btinfo h.btstep h.btclose h.btplay h.btreset h.btload h.pualgo ...
            h.btcreat h.editer h.edprec h.xbanim],'Enable','off');

      % Only stop button can be pushed down
      set(h.btstop,'Enable','on');

      % Stop button was not pushed down
      set(h.btstop,'UserData',0);
      play=1;

      % get arguments from dialog
      anim=get(h.xbanim,'Value');

      % Play - adaptation process
      while play==1 & get(h.btstop,'UserData')==0,

         % get arguments from dialog
         oldtheta=h.line.theta;
         oldalpha=h.line.alpha;

         % call algorithm
         [h,text,play,solution]=callalgo(h,sets);

         % appear result
         set(h.console,'String',text );
         drawnow;

         if play~=-1,
            % plot result
            if h.line.handler==-1,
               axes(h.axes1);
               h.line.handler=feval(PLOT_FCE,sets.MI,sets.SIGMA,sets.I,...
                  h.line.alpha,h.line.theta );
            else
               feval(PLOT_FCE,sets.MI,sets.SIGMA,sets.I,h.line.alpha,h.line.theta,...
                  h.line.handler,anim,oldalpha,oldtheta);
            end
         end

         % hands on control to MATLAB
         drawnow;
      end % while play == 1 & get(...

      %  store new solution
      set(hfigure,'UserData',h);

      % enable these buttons
      set([h.btinfo h.btstep h.btclose h.btplay h.btreset h.btload ...
         h.btcreat h.pualgo h.editer h.edprec h.xbanim],'Enable','on');

      % disable stop button
      set(h.btstop,'Enable','off');

   else % isempty(sets)==0,
      % write down description
      text=sprintf('No data loaded.\nPress Load data button.\n');
      set(h.console,'String',text );
   end


case 'step'
   % == Perform one adaptation step ================================================
   h=get(hfigure,'UserData');                     % get handlers we will need...

   % get sets
   sets=get(h.axes1,'UserData');

   % if some set is loaded then perform on step
   if isempty(sets)==0,

      % get arguments from dialog
      anim=get(h.xbanim,'Value');
      oldtheta=h.line.theta;
      oldalpha=h.line.alpha;

      % call algorithm
      [h,text,play,solution]=callalgo(h,sets);

      % appear result
      set(h.console,'String',text );
      drawnow;

      if play~=-1,
         % plot result
         if h.line.handler==-1,
            axes(h.axes1);
            h.line.handler=feval(PLOT_FCE,sets.MI,sets.SIGMA,sets.I,...
               h.line.alpha,h.line.theta );
         else
            feval(PLOT_FCE,sets.MI,sets.SIGMA,sets.I,h.line.alpha,...
               h.line.theta,h.line.handler,anim,oldalpha,oldtheta);
         end
      end

      drawnow;

      % store data
      set(hfigure,'UserData',h);

   else % isempty(sets)==0,
      % write down description
      text=sprintf('No data loaded.\nPress Load data button.\n');
      set(h.console,'String',text );
   end

case 'reset'
   % == Reset adaptation process ==================================
   % Sets t=0 and redraws axes.

   h=get(hfigure,'UserData');                     % get handlers

   % zeroize all parameters of the solution
   h.line.t=0;
   h.line.theta=0;
   h.line.alpha=[0;0];
   h.line.alpha1=[0;0];
   h.line.alpha2=[0;0];
   h.line.lambda=0;
   set(hfigure,'UserData',h);

   % No line
   h.line.handler=-1;
   set(hfigure,'UserData',h);
   %%%   cla;
   clrchild(h.axes1);
   %%%   win=axis;
   win=getaxis(h.axes1);
   %%%   axis([0 1 0 1]);
   setaxis(h.axes1,[0 1 0 1]);
   %%%   axis(win);
   setaxis(h.axes1,win);

   % Redraw points
   sets=get(h.axes1,'UserData');

   % if some points are loaded than appear it
   if isempty(sets)==0,

      % set axes according to current points MI

      if sum(sets.K) < 3,
         win=cmpwin(min(sets.MI'),max(sets.MI'),BORDER*2,BORDER*2);
      else
         win=cmpwin(min(sets.MI'),max(sets.MI'),BORDER,BORDER);
      end

      %%% axis(win);
      setaxis(h.axes1,win);

%%      pplot(sets.MI,sets.I);
      ppoints(sets.MI,sets.I);

      % comment window text
      consoletext=sprintf('Step t=0\nNo separation line');

      file=get(h.btload,'UserData');
      titletext=sprintf('File: %s, # of distributions K = %d',file.name,sum(sets.K));

   else % if isempty(sets)==0,
      % comment window text
      consoletext=sprintf('No data loaded.\nPress Load data button.\n');
      titletext='';

      pos=get(h.axes1,'Position');
      fsize=min(pos(3),pos(4))/10;

      %%%      axis([-1 1 -1 1]);
      setaxis(h.axes1,[-1 1 -1 1]);
      builtin('text',0,0,'Press ''Load data'' button.',...
         'HorizontalAlignment','center',...
         'FontUnits','normalized',...
         'Clipping','on',...
         'FontSize',fsize);
   end

   % print comment
   set(h.console,'String',consoletext );

   % print title
   pos=get(h.axes1,'Position');
   fsize=(1-pos(2)-pos(4))*1;
   title(titletext,...
      'VerticalAlignment','bottom',...
      'HorizontalAlignment','left',...
      'FontUnits','normalized',...
      'Units','normalized',...
      'Position',[0 1 0],...
      'FontSize',fsize);


case 'info'
   % == Call standard Matlab info box =========================================
   helpwin(mfilename);


end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h,text,play,solution]=callalgo(h,sets)

% get arguments from dialog
precision=str2num(get(h.edprec,'String'));
iter=max([1,fix(str2num(get(h.editer,'String')))]);

% get parameters
t=h.line.t;
alpha=h.line.alpha;
alpha1=h.line.alpha1;
alpha2=h.line.alpha2;
lambda=h.line.lambda;
theta=h.line.theta;

% perform algorithm
switch get(h.pualgo,'Value')
case 4
   % General solution
   [nalpha,ntheta,solution,minr,nt,maxerr]=...
      ganders(sets.MI,sets.SIGMA,sets.I,iter,precision,t,alpha,theta);
   text=sprintf('Step t=%d\nLine [%f , %f]*x=%f\nMinimal r = %.15f, Max error = %f%%',...
      nt,nalpha(1),nalpha(2),ntheta,minr,maxerr*100);
case 1
   % e-Optimal solution
   [nalpha,ntheta,solution,nt,alpha1,alpha2]=...
       eanders(sets.MI,sets.SIGMA,sets.I,iter,precision/100,t,alpha1,alpha2);
    if sum(nalpha)==0,
      solution=-1;
      nalpha=alpha;
      ntheta=theta;
   end
   text=sprintf('Step t=%d\nLine [%f , %f]*x=%f',nt,nalpha(1),nalpha(2),ntheta);
case 2
   % Original Anderson`s solution
   [nalpha,ntheta,solution,nt,lambda,ni,maxerr]=...
      oanders(sets.MI,sets.SIGMA,sets.I,iter,precision,t,lambda);
   text=sprintf(...
      'Step t=%d\nLine [%f , %f]*x=%f\nNi = %f, (1-Lambda)/Lambda = %f, Max error = %f%%',...
      nt,nalpha(1),nalpha(2),ntheta,ni,(1-lambda)/lambda,maxerr*100);
case 5
   % General 2
   [nalpha,ntheta,solution,minr,nt,maxerr]=...
   ganders2(sets.MI,sets.SIGMA,sets.I,iter,precision,t,alpha,theta);
   text=sprintf('Step t=%d\nLine [%f , %f]*x=%f\nMinimal r = %.15f, Max error = %f%%',...
      nt,nalpha(1),nalpha(2),ntheta,minr,100*maxerr);
case 3
   % Gradient method
   [nalpha,ntheta,solution,minr,nt,maxerr]=...
      gganders(sets.MI,sets.SIGMA,sets.I,iter,precision,t,alpha,theta);
   text=sprintf('Step t=%d\nLine [%f , %f]*x=%f\nMinimal r = %.15f, Max error = %f%%',...
      nt,nalpha(1),nalpha(2),ntheta,minr,maxerr*100);
end

if solution==-1,
    text=sprintf('Solution does not exist.\n');
    play=-1;
    return;
elseif solution==1,
   text=strvcat(text,sprintf('Solution was found in %d step(s)',nt));
   play=0;
else
   play=1;
end

% store new values
h.line.t = nt;
h.line.alpha = nalpha;
h.line.alpha1 = alpha1;
h.line.alpha2 = alpha2;
h.line.lambda = lambda;
h.line.theta = ntheta;

return